$(function(){

	Vue.config.debug = true;

	//配置emo api信息
	API.config.token = "5af9992437dbbe7c0aa2c1887ddaf73a";
	API.config.server = "http://api.ohemo.com/kata";
	API.user =  {
					"cover_img": "http://7xkusq.com2.z0.glb.qiniucdn.com/cover/45c0c75d8c3bf7a083bb729ba26ffefd.jpg",
					"head": "http://kata-room.b0.upaiyun.com/c0d34f440dce0a205e777e08ae0e65f4.jpg",
					"intro": "\u4e00\u4e2a\u559c\u6b22\u72ec\u5904\u7684\u4eba",
					"name": "\u6881\u6653\u6668",
					"id": "28515"
				};
	//列表-单个feed组件
	var EmoListItem = Vue.extend({
		template: '<li class="feed-wrapper" v-on="doubleTap:like()">' + 
				'<div class="user-info">' + 
					'<img class="avatar" v-attr="src:feed.user.head"></img>' + 
					'<span class="name">{{feed.user.name}}</span><span class="time">{{new Date().format(feed.publish_time)}}</span>' + 
				'</div>' + 
				'<div class="image-wrapper"><img v-attr="src:feed.image.url" v-if="feed.image.url">' + 
				'<img class="repost" v-attr="data-original:feed.repost.repost_image.url" v-if="feed.repost" v-link="/photo/{{feed.repost.repost_id}}"></div>' + 
				'<div class="feed-info">' + 
					'<p class="text" v-html="feed.content"></p>' + 
					'<p class="location">{{feed.location}}</p>' + 
					'<div class="feed-extras">' + 
						'<span v-on="touchstart:like()"><i v-class="icon-heart:feed.is_like,icon-heart-empty:!feed.is_like"></i>{{feed.like_count}}</span>' + 
						'<span class="comment" v-on="touchstart:comment()"><i class="icon-comments-alt"></i>{{feed.comment_count}}</span>' + 
					'</div>' + 
				'</div>' + 
			'</li>',

		props: ['feed'],

		methods: {
			like: function() {
				this.feed.is_like = !this.feed.is_like;
				this.feed.like_count += this.feed.is_like?1:-1;
				API.like(this.feed.id, this.feed.is_like, function(data) {
					// console.log(data);
				});
			},
			comment: function() {
				localStorage.setItem('transData', JSON.stringify(this.feed));
				router.go('/comments');
			}
		},

		beforeCompile: function() {
			// console.log(this.feed)
			if (this.feed && this.feed.content) {
				this.feed.content = this.feed.content.replace(/\#([^\#|.]+)\#/g,"<span class='topic'>#$1#</span>");
			}
			// if (this.feed) {
			// 	this.$data = this.feed;
			// }
			// console.log(this)
		}

	});

	var EmoPhoto = Vue.extend({
		template: '<div class="page">' +
     '<div class="nav-bar fixed"><a class="back" v-link="/feedlist"><i class="icon-angle-left"></i></a><p>照片</p></div>' +
     '<div class="page-body" v-style="background-image:\'url(./images/bg.jpg)\'">' +
     '<div v-component="emo-list-item" feed="{{feed}}"></div>' + 
     '</div>' + 
     '</div>',
     components: {
     	'emo-list-item': EmoListItem
     },
     data: function() {
     	return {
     		feed: {
     			user: {},
     			image: {}
     		}
     	}
     },

     beforeCompile: function() {
     	// var feed = JSON.parse(localStorage.getItem('transData'));
     	API.getFeed(this.$route.params.fid, (function(data) {
     		var feed = JSON.parse(data).data;
     		this.feed = feed;
     	}).bind(this));
     },

     compiled: function() {

     }
	});

	//评论组件
	var EmoComments = Vue.extend({

		template: '<div class="comments-box">' + 
			'<span class="close" v-on="touchstart:back()"><i class="icon-angle-left"></i></span>' + 
			'<div class="bg" v-if="feed" style="background-image:url({{feed.image.url}});"></div>' + 
			'<ul class="comment-list">' + 
				'<li class="comment-wrapper" v-transition="fade" v-on="longTap:del(cmt),touchstart:at(cmt, $event)" v-repeat="cmt in comments" v-class="mine:cmt.user.id==me.id,topic-owner:feed.user.id==cmt.user.id">' + 
					'<span class="name">{{cmt.user.name}}</span>' + 
					'<p class="time">{{new Date().format(cmt.date, true)}}</p>' + 
					'<img class="avatar" v-attr="src:cmt.user.head"></img>' + 
					'<div class="comment">{{cmt.text}}</div>' + 
				'</li>' +
			'</ul>' + 
			'<div class="comment-input">' + 
				'<img class="avatar" v-attr="src:me.head"/>' + 
				'<textarea v-on="keydown:onTextChange" v-model="content" autofocus></textarea>' + 
			'</div>' + 
		'</div>',

		data: function() {
			return {
				comments: {},
				me: API.user,
				feed: {
					image: {}
				},
				content: ""
			}
		},

    beforeCompile: function() {
      var feed = JSON.parse(localStorage.getItem('transData'));
      this.feed = feed;
    },

		compiled: function() {
      console.log('EmoComments Compiled');
			
			// console.log(this.feed);
			API.getCommentList(this.feed.id, (function(data) {
				// console.log(data);
				data = JSON.parse(data);
				this.comments = data.data.comments.sort(function(item) {
					return item.date;
				});
			}).bind(this));
		},

		methods: {

			at: function(cmt, event) {
				this.content += '@' + cmt.user.name + " ";
			},

			publish: function(text, done) {
				API.comment(this.feed.id, text, (function(data) {
					done();
					data = JSON.parse(data);
					this.comments.push(data.data.comment);
					this.comments = this.comments.sort(function(item) {
						return -item.date;
					});
				}).bind(this));
			},

			del: function(cmt) {
				if (cmt.user.id != API.user.id) return;
				API.delComment(cmt.id, (function() {
					this.comments = _.reject(this.comments, function(_cmt) {
						return _cmt.id == cmt.id;
					});
				}).bind(this));
			},

			back: function() {
				history.back();
			},

			onTextChange: function(event) {
				if (event.keyCode == 13) {
					var text = event.target.value.trim();
					this.publish(text, function() {
						event.target.value = "";
					});
				}
			}
		}
	});

	var EmoPublish = Vue.extend({
		template: '<div class="page"><div class="nav-bar"><a class="back" v-link="/feedlist"><i class="icon-angle-left"></i></a><p>@{{user.name}}</p><a v-on="touchstart:publish()">发布</a></div>' + 
		'<div class="post-box">' +
			'<div class="content"><textarea placeholder="说点什么吧" v-model="input" maxLength="150"></textarea></div>' + 
			'<div class="count">{{count - input.length}}/150</div>' +
			'<div class="pic" v-class="uploaded:file"><img v-attr="src:imageUrl"/><input type="file" v-el="file" v-show="!file" v-model="file"/></div>' + 
			'</div></div>',
		data: function() {
			return {
				user: API.user,
				count: 150,
				input: "",
				imageUrl: "",
				file: ""
			}
		},
		methods: {
			publish: function() {
				API.publish(this.input, this.imageUrl, function() {
					window.history.back();
				});
			}
		},

		watch: {
			'file': function(val) {
				API.uploadImage(this.$$.file, (function(data) {
					console.log(data);
					this.imageUrl = 'http://7sbmdw.com1.z0.glb.clouddn.com/' + data.key;
				}).bind(this));
			}
		}
	});

	//消息列表
	var EmoMsgItem = Vue.extend({
		template: '<div class="page">' +
     '<div class="nav-bar fixed"><a class="back" v-link="/feedlist"><i class="icon-angle-left"></i></a><p>消息</p></div>' +
     '<div class="page-body" v-on="scroll:scroll">' +
       '<ul class="message-list">' +
         '<li v-repeat="item in list" data-id="{{item.id}}">' +
           '<img class="avatar" v-attr="src:item.user.head">' +
           '<div class="content" v-on="tap:goCmt(item.feed)">' +
             '<p><span>{{item.user.name}}</span>' +
             '<span v-if="item.subtype==0&&item.type==1&&item.relation==99">关注了你，想要互相关注么？</span><span v-if="item.subtype==0&&item.type==1">赞了你的照片</span><span v-if="item.subtype==0&&item.type==6">评论了你的照片</span><span v-if="item.subtype==1&&item.type==6">也评论了该照片</span><span v-if="item.subtype==2&&item.type==6">回复了你的评论</span></p>' +
             '<p>{{item.content}}</p>' +
             '<p class="meta">{{new Date().format(item.time)}}</p>' +
           '</div>' +
           '<div class="thumbnail"><img v-attr="src:item.feed.image.url" v-link="/photo/{{item.feed.id}}"></div>' +
         '</li>' +
       '</ul>' +
     '</div>' +
    '</div>',

    data: function() {
    	return {
    		list: [],
    		hasMore: false,
    		data: {}
    	}
    },

    methods: {
    	goCmt: function(feed) {
    		localStorage.setItem('transData', JSON.stringify(feed));
    		router.go('/comments')    	
    	},

    	scroll: function(event) {
    		var target = event.target;
    		if (target.clientHeight + target.scrollTop == target.scrollHeight) {
    			this.loadMessage(this.data.last_mid);
    		}
    	},

    	loadMessage: function(lastMid) {
    		API.getMessageList(lastMid, (function(data) {
    			this.data = JSON.parse(data).data;
    			this.list = this.list.concat(this.data.message_list);
    			this.hasMore = !!this.data.has_more;
    		}).bind(this));
    	}
    },

    compiled: function() {
    	var _this = this;
    	this.loadMessage(null);
    }

	});


	//头部个人信息
	var UserHead = Vue.extend({
		template: '<div class="mine-head"><a><img v-attr="src:user.head"/></a><a class="title" v-link="/messagelist">{{user.name}}<span v-show="postCount>0" class="dot">{{postCount}}</span></a></div>',
		props: ['postCount'],
		data: function() {
			return {
				user: API.user
			}
		}
	});

	var OpMenu = Vue.extend({
		template: '<div class="bottom-menu"><a class="op-icon op-camera" v-link="/publish"><i class="icon-camera"></i></a></div>',
	});

	// 列表组件
	var List = Vue.extend({

		template: '<emo-mine-head post-count="{{postCount}}"></emo-mine-head><ul class="feed-list"><li v-repeat="feed in feedList" v-component="emo-list-item"></li></ul><emo-op-menu></emo-op-menu>',

		data: function() {
			return {
				commentShow: false,
				feedList: [],
				postCount: 0
			};
		},

		components: {
			'emo-list-item': EmoListItem,
			'emo-mine-head': UserHead,
			'emo-op-menu': OpMenu,
			'emo-message-list': EmoMsgItem
		},

		compiled: function() {
			var _this = this;
      console.log('List Compiled');
			API.getFeedList(0, function(data) {
				data = JSON.parse(data);
				_this.feedList = data.data.feed_list;
				setTimeout(function() {
					$(".feed-list img").picLazyLoad();
				}, 100)
			});

			API.getPostCount(function(data) {
				data = JSON.parse(data);
				_this.postCount = data.data.count;
			});
		},


	});

	//注册路由
	var router = window.router = new VueRouter({
		// history: true,
  		saveScrollPosition: true
	});
	router.map({
		'/': {
			component: List
		},
		'/feedlist': {
			component: List
		},
		'/comments': {
			component: EmoComments
		},
		'/publish': {
			component: EmoPublish
		},
		'/messagelist': {
			component: EmoMsgItem
		},
		'/photo/:fid': {
			component: EmoPhoto
		}
	});
	
	//启动EMO APP
	var App = Vue.extend({});
	router.start(App, '#app');
	window.app = router.app;

});
